﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using KProtectProcess;

namespace VirusCleaner.Tray
{
    static class Program
    {
        #region 启动程序
        static Process ApplicationProcess;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.SetCompatibleTextRenderingDefault(false);            
            //是否有参数传递
            if (args.Length > 0)
            {
                switch (args[0])
                {
                    //如果来自于主程序窗体
                    case "/main":
                        //启动
                        ApplicationProcess = RunApplication();
                        break;
                    //启动项
                    case "/runkey":
                        //处理代码

                        break;
                    default:
                        MessageBox.Show(string.Format("不支持的调用参数:\n{0}", args[0]), "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        break;
                }
            }
            //如果可能,获得正在运行的实例
            Process instance = RunningInstance();
            //如果实例不存在
            if (instance == null)
            {
                Application.Run(new FrmTray());
            }
        }
        #endregion


        #region 运行程序


        public static Process RunApplication()
        { 
            return RunApplication("/tray"); 
        }
        /// <summary>
        /// 调用主程序[参数]
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        public static Process RunApplication(string arg = "/tray")
        {
            Process process = Process.Start("VirusCleaner.exe", arg);
            //确认订阅事件
            process.EnableRaisingEvents = true;
            //程序退出事件
            process.Exited += new EventHandler(process_Exited);
            //保护运行的进程
            KProcess.ProtectProcessID = (uint)process.Id;
            //开始保护
            if (KProcess.ProtectProcess())
            {
                //保护进程,防止被破坏
                ApplicationProcess = process;
            }
            return process;
        }
        static void process_Exited(object sender, EventArgs e)
        {
            //保护自身进程
            if (KProcess.SelfProtection())
            {
                //销毁
                ApplicationProcess = null;
            };
        }
        #endregion
        #region 退出程序
        /// <summary>
        /// 退出程序
        /// </summary>
        public static void ExitApplication()
        {
            if (KProcess.UnLoadProtection())//卸载保护
            {
                //主程序是否运行
                if (ApplicationProcess != null)
                {
                    //结束进程
                    ApplicationProcess.Kill();
                }
            }
            Application.ThreadExit += new EventHandler(Application_ThreadExit);
            Application.ExitThread();//退出
        }

        static void Application_ThreadExit(object sender, EventArgs e)
        {
            ProcessStartInfo info = new ProcessStartInfo();
            info.FileName = "taskkill";
            //清理进程列表<临时解决方案>
            info.Arguments = string.Format("-im {0} -f", "viruscleanertray.exe");
            info.WindowStyle = ProcessWindowStyle.Hidden;
            Process.Start(info);
        }
        #endregion  
        #region 激活程序
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private const int WS_SHOWNORMAL = 1;

        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);

            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==
                        current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }
        #endregion
    }
}